<template>
  <div class="app-container">
    <el-form ref="queryParams" inline size="mini" :model="queryParams">
      <el-form-item label="用户名称">
        <el-input />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="getTableDataByFirst">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10">
      <el-col :span="2">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-plus"
          @click="onOpenAddUserModal"
        >新增</el-button>
      </el-col>
    </el-row>

    <section class="table_group">
      <el-table :data="tableData" max-height="500">
        <el-table-column type="selection" />
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="用户名称" prop="user_name" />
        <el-table-column label="用户昵称" prop="nick_name" />
        <el-table-column label="部门" prop="dept.dept_name" />
        <el-table-column label="手机号码" prop="phonenumber" />
        <el-table-column label="状态" prop="status" />
        <el-table-column label="创建时间" prop="create_time" />
        <el-table-column label="操作" />
      </el-table>
      <pagination :total="pagination.total" :limit="pagination.limit" :page="pagination.page" @pagination="onPagination" />
    </section>

    <!--添加或修改用户信息-->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="userForm" label-width="80px" :model="userForm">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="用户昵称">
              <el-input v-model="userForm.nick_name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门">
              <treeselect v-model="userForm.dept_id" :normalizer="normalizer" placeholder="请选择上级部门" :options="treeDept" :show-count="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码">
              <el-input v-model="userForm.phonenumber" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="userForm.email" />
            </el-form-item>
          </el-col>
          <template v-if="userForm.user_id === undefined">
            <el-col :span="12">
              <el-form-item label="用户名称">
                <el-input v-model="userForm.user_name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户密码">
                <el-input v-model="userForm.password" />
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="userForm.sex">
                <el-option :value="0" label="男" />
                <el-option :value="1" label="女" />
                <el-option :value="2" label="未知" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="userForm.status">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="userForm.post_ids" multiple>
                <el-option v-for="post in post_code_list" :key="post.post_id" :value="post.post_id" :label="post.post_name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="userForm.role_ids" multiple>
                <el-option v-for="role in role_code_list" :key="role.role_id" :value="role.role_id" :label="role.role_name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="userForm.remark" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="open = false">取 消</el-button>
        <el-button size="small" type="primary" @click="onAddOrModifyUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import { getActivePostApi } from '@/api/post'
import { getActiveRolesApi } from '@/api/role'
import { getTreeDeptApi } from '@/api/dept'
import { addUserApi, modifyUserApi, getUserListApi } from '@/api/user'
export default {
  name: 'User',
  components: { Pagination, Treeselect },
  data() {
    return {
      loading: false,
      queryParams: {},

      title: '',
      open: false,
      userForm: {},
      post_code_list: [],
      role_code_list: [],
      treeDept: [],
      normalizer(node) {
        return {
          id: node.dept_id,
          label: node.dept_name,
          children: node.children
        }
      },

      tableData: [],
      pagination: {
        total: 0,
        limit: 20,
        page: 1
      }
    }
  },
  created() {
    this.getTableDataByFirst()
  },
  methods: {
    indexMethod(index) {
      return (index + 1) + ((this.pagination.page - 1) * this.pagination.limit)
    },
    /**
     * 分页数据改变
     */
    onPagination({ page, limit }) {
      if (this.pagination.limit !== limit) {
        this.pagination.limit = limit
        this.getTableDataByFirst()
      } else {
        this.pagination.page = page
        this.onGetTableData()
      }
    },

    /**
     * 获取首页查询
     */
    getTableDataByFirst() {
      this.pagination.page = 1
      this.onGetTableData()
    },

    /**
     * 获取岗位列表
     */
    onGetTableData() {
      this.loading = true
      const params = {
        ...this.queryParams,
        page_num: this.pagination.page,
        page_size: this.pagination.limit
      }

      getUserListApi(params).then((res) => {
        this.loading = false
        if (res && res.code === 0) {
          this.tableData = res.data.rows
          this.pagination.total = res.data.count
        }
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 重置用户添加或修改表单
     */
    resetUserForm() {
      this.userForm = {
        user_id: undefined,
        dept_id: undefined, // 部门id
        user_name: undefined, // 登录Id
        password: undefined, // 密码
        nick_name: undefined, // 用户昵称
        phonenumber: undefined, // 手机号
        email: undefined, // 邮箱
        sex: undefined, // 性别
        avatar: undefined, // 头像
        status: 1, // 用户状态
        remark: undefined, // 备注
        role_ids: [], // 角色ids
        post_ids: [] // 岗位ids
      }

      this.$resetForm('userForm')

      getActivePostApi().then((res) => {
        if (res && res.code === 0) {
          this.post_code_list = res.data
        }
      })

      getActiveRolesApi().then((res) => {
        if (res && res.code === 0) {
          this.role_code_list = res.data
        }
      })

      getTreeDeptApi().then((res) => {
        if (res && res.code === 0) {
          this.treeDept = res.data
        }
      })
    },

    /**
     * 打开新增表单弹窗
     */
    onOpenAddUserModal() {
      this.resetUserForm()
      this.title = '创建用户'
      this.open = true
    },

    /**
     * 打开修改表单弹窗
     * @param index 当前角色数组索引
     * @param post 当前角色信息
     */
    onOpenModifyUserModal(index, role) {
      this.resetUserForm()
      this.onGetTreeMenu()
      this.userForm = { ...role, status: +role.status }
      this.title = '修改角色'
      this.open = true
      this.$nextTick(() => {
        this.$refs.menu.setCheckedKeys(role.menu_ids)
      })
    },

    /**
     * 新增或修改用户信息
     */
    onAddOrModifyUser() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          const params = {
            user_id: this.userForm.user_id,
            dept_id: this.userForm.dept_id,
            user_name: this.userForm.user_name,
            nick_name: this.userForm.nick_name,
            email: this.userForm.email,
            phonenumber: this.userForm.phonenumber,
            sex: this.userForm.sex,
            avatar: this.userForm.avatar,
            status: this.userForm.status,
            remark: this.userForm.remark,
            role_ids: this.userForm.role_ids,
            post_ids: this.userForm.post_ids
          }
          // 新增角色
          if (this.userForm.role_id === undefined) { // 新增岗位
            addUserApi(params).then((res) => {
              if (res && res.code === 0) {
                this.open = false
                this.$message.success(res.msg)
                this.onGetTableData()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else { // 修改角色
            // 修改部门
            modifyUserApi(params).then((res) => {
              if (res && res.code === 0) {
                this.open = false
                this.$message.success(res.msg)
                this.onGetTableData()
                this.onGetTreeMenu()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
